package cn.snailhd.core.base.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.snailhd.core.base.constant.ConfigConstant;
import cn.snailhd.core.base.dao.RedisDao;
import cn.snailhd.core.base.domain.UserTokenDO;
import cn.snailhd.utils.AESUtil;
import cn.snailhd.utils.string.StringUtils;



@Service
public class TokenService {
	
	
	@Autowired
	RedisDao redis;
	

	public String saveToken(String userid) throws Exception{
		UserTokenDO tokenDO = new UserTokenDO();
		tokenDO.setUserid(userid);
		tokenDO.setLoginid(StringUtils.guid18());
		String text = JSON.toJSONString(tokenDO);
		String token = AESUtil.encry(text, ConfigConstant.AES_KEY);
		
		redis.set(ConfigConstant.getRedisKeyLoginToken(tokenDO.getUserid()), text);
		
		return token;
	}
	
	
	
	public String verifyToken(String token,boolean required) throws Exception{
		String re = AESUtil.decry(token, ConfigConstant.AES_KEY);
		UserTokenDO tokenDO = JSON.parseObject(re,UserTokenDO.class);
		String userid = tokenDO.getUserid();
		String token_text = redis.get(ConfigConstant.getRedisKeyLoginToken(tokenDO.getUserid()));
		return userid;
	}

}
